package com.leicx.guli.product.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.leicx.guli.common.constant.ParamConstant;
import com.leicx.guli.common.enums.ProductStatusEnum;
import com.leicx.guli.common.to.SkuReductionTo;
import com.leicx.guli.common.to.SpuBoundTo;
import com.leicx.guli.common.to.es.SkuEsModel;
import com.leicx.guli.common.utils.CommonPageQueryUtil;
import com.leicx.guli.common.utils.FeignUtil;
import com.leicx.guli.common.utils.PageUtils;
import com.leicx.guli.common.utils.Query;
import com.leicx.guli.common.utils.R;
import com.leicx.guli.common.vo.SkuHasStockVo;
import com.leicx.guli.product.dao.SpuInfoDao;
import com.leicx.guli.product.entity.BrandEntity;
import com.leicx.guli.product.entity.CategoryEntity;
import com.leicx.guli.product.entity.ProductAttrValueEntity;
import com.leicx.guli.product.entity.SkuImagesEntity;
import com.leicx.guli.product.entity.SkuInfoEntity;
import com.leicx.guli.product.entity.SkuSaleAttrValueEntity;
import com.leicx.guli.product.entity.SpuInfoDescEntity;
import com.leicx.guli.product.entity.SpuInfoEntity;
import com.leicx.guli.product.feign.CouponFeignService;
import com.leicx.guli.product.feign.SearchFeignService;
import com.leicx.guli.product.feign.WareFeignService;
import com.leicx.guli.product.service.AttrService;
import com.leicx.guli.product.service.BrandService;
import com.leicx.guli.product.service.CategoryService;
import com.leicx.guli.product.service.ProductAttrValueService;
import com.leicx.guli.product.service.SkuImagesService;
import com.leicx.guli.product.service.SkuInfoService;
import com.leicx.guli.product.service.SkuSaleAttrValueService;
import com.leicx.guli.product.service.SpuImagesService;
import com.leicx.guli.product.service.SpuInfoDescService;
import com.leicx.guli.product.service.SpuInfoService;
import com.leicx.guli.product.vo.attr.AttrRespVo;
import com.leicx.guli.product.vo.spu.save.Attr;
import com.leicx.guli.product.vo.spu.save.BaseAttrs;
import com.leicx.guli.product.vo.spu.save.Bounds;
import com.leicx.guli.product.vo.spu.save.Images;
import com.leicx.guli.product.vo.spu.save.Skus;
import com.leicx.guli.product.vo.spu.save.SpuSaveVo;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Date;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.Set;
import java.util.stream.Collectors;


@Service("spuInfoService")
public class SpuInfoServiceImpl extends ServiceImpl<SpuInfoDao, SpuInfoEntity> implements SpuInfoService {

    @Resource
    SpuInfoDescService spuInfoDescService;
    @Resource
    SpuImagesService spuImagesService;
    @Resource
    AttrService attrService;
    @Resource
    ProductAttrValueService productAttrValueService;
    @Resource
    SkuInfoService skuInfoService;
    @Resource
    SkuImagesService skuImagesService;
    @Resource
    SkuSaleAttrValueService skuSaleAttrValueService;
    @Resource
    CouponFeignService couponFeignService;
    @Resource
    BrandService brandService;
    @Resource
    CategoryService categoryService;
    @Resource
    WareFeignService wareFeignService;
    @Resource
    SearchFeignService searchFeignService;

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<SpuInfoEntity> page = this.page(
                new Query<SpuInfoEntity>().getPage(params),
                new QueryWrapper<SpuInfoEntity>()
        );

        return new PageUtils(page);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void saveSpuInfo(SpuSaveVo spuSaveVo) {
        // 1.保存基本信息
        SpuInfoEntity spuInfoEntity = BeanUtil.copyProperties(spuSaveVo, SpuInfoEntity.class);
        this.saveBaseSupInfo(spuInfoEntity);
        // 2.保存spu描述
        List<String> decript = spuSaveVo.getDecript();
        SpuInfoDescEntity spuInfoDescEntity = new SpuInfoDescEntity();
        spuInfoDescEntity.setSpuId(spuInfoEntity.getId());
        spuInfoDescEntity.setDecript(String.join(",", decript));
        spuInfoDescService.save(spuInfoDescEntity);
        // 3.保存spu图片集
        List<String> images = spuSaveVo.getImages();
        spuImagesService.saveSpuImages(spuInfoEntity.getId(), images);
        // 4.保存spu的规格参数
        List<BaseAttrs> baseAttrs = spuSaveVo.getBaseAttrs();
        List<ProductAttrValueEntity> collect = baseAttrs.stream().map(q -> {
            ProductAttrValueEntity productAttrValueEntity = new ProductAttrValueEntity();
            productAttrValueEntity.setAttrId(q.getAttrId());
            AttrRespVo attrInfo = attrService.getAttrInfo(q.getAttrId());
            productAttrValueEntity.setAttrName(attrInfo.getAttrName());
            productAttrValueEntity.setAttrValue(q.getAttrValues());
            productAttrValueEntity.setQuickShow(q.getShowDesc());
            productAttrValueEntity.setSpuId(spuInfoEntity.getId());
            return productAttrValueEntity;
        }).collect(Collectors.toList());
        productAttrValueService.saveBatch(collect);
        // 5.保存spu的积分信息
        Bounds bounds = spuSaveVo.getBounds();
        SpuBoundTo spuBoundTo = new SpuBoundTo(spuInfoEntity.getId(), bounds.getBuyBounds(), bounds.getGrowBounds());
        couponFeignService.saveSpuBounds(spuBoundTo);
        // 5.保存当前spu对应的所有sku信息
        List<Skus> skus = spuSaveVo.getSkus();
        if (CollUtil.isNotEmpty(skus)) {
            skus.forEach(q -> {
                // 5.1 sku基本信息
                String defaultImageUrl = q.getImages().stream()
                        .filter(item -> Objects.equals(item.getDefaultImg(), 1))
                        .map(Images::getImgUrl)
                        .findFirst().orElse("");
                SkuInfoEntity skuInfoEntity = BeanUtil.copyProperties(q, SkuInfoEntity.class);
                skuInfoEntity.setBrandId(spuInfoEntity.getBrandId());
                skuInfoEntity.setCatalogId(spuInfoEntity.getCatalogId());
                skuInfoEntity.setSaleCount(0L);
                skuInfoEntity.setSpuId(spuInfoEntity.getId());
                skuInfoEntity.setSkuDefaultImg(defaultImageUrl);
                skuInfoService.save(skuInfoEntity);

                // 5.2 sku的图片信息
                List<SkuImagesEntity> skuImages = q.getImages().stream().map(img -> {
                    SkuImagesEntity skuImagesEntity = BeanUtil.copyProperties(img, SkuImagesEntity.class);
                    skuImagesEntity.setSkuId(skuInfoEntity.getSkuId());
                    return skuImagesEntity;
                }).filter(m -> StrUtil.isNotEmpty(m.getImgUrl())).collect(Collectors.toList());
                skuImagesService.saveBatch(skuImages);

                // 5.3 sku的销售属性信息
                List<Attr> attr = q.getAttr();
                List<SkuSaleAttrValueEntity> list = attr.stream().map(a -> {
                    SkuSaleAttrValueEntity skuSaleAttrValueEntity = BeanUtil.copyProperties(a, SkuSaleAttrValueEntity.class);
                    skuSaleAttrValueEntity.setSkuId(skuInfoEntity.getSkuId());
                    return skuSaleAttrValueEntity;
                }).collect(Collectors.toList());
                skuSaleAttrValueService.saveBatch(list);

                // 5.4 sku的优惠满减等信息
                SkuReductionTo skuReductionTo = BeanUtil.copyProperties(q, SkuReductionTo.class);
                skuReductionTo.setSkuId(skuInfoEntity.getSkuId());
                couponFeignService.saveSkuReduction(skuReductionTo);
            });
        }

    }

    @Override
    public void saveBaseSupInfo(SpuInfoEntity spuInfoEntity) {
        if (spuInfoEntity.getCreateTime() == null) {
            spuInfoEntity.setCreateTime(new Date());
        }
        if (spuInfoEntity.getUpdateTime() == null) {
            spuInfoEntity.setUpdateTime(new Date());
        }
        save(spuInfoEntity);
    }

    @Override
    public PageUtils queryPageByCondition(Map<String, Object> params) {
        QueryWrapper<SpuInfoEntity> queryWrapper = new QueryWrapper<>();
        CommonPageQueryUtil.setKeyQuery(queryWrapper, params,
                ParamConstant.ID, ParamConstant.SPU_NAME);
        CommonPageQueryUtil.setNormalEqQuery(queryWrapper, params, ParamConstant.STATUS, "publish_status");
        CommonPageQueryUtil.setNormalEqQuery(queryWrapper, params, "brandId", ParamConstant.BRAND_ID);
        CommonPageQueryUtil.setNormalEqQuery(queryWrapper, params, "catalogId", "catalog_id");
        IPage<SpuInfoEntity> page = this.page(
                new Query<SpuInfoEntity>().getPage(params),
                queryWrapper
        );
        return new PageUtils(page);
    }

    @Override
    public void up(Long spuId) {
        // 获取spuId下的所有sku信息，包括品牌的名字
        List<SkuInfoEntity> skus = skuInfoService.getSkusBySpuId(spuId);
        SpuInfoEntity spuInfo = getById(spuId);
        BrandEntity brand = brandService.getById(spuInfo.getBrandId());
        CategoryEntity category = categoryService.getById(spuInfo.getCatalogId());

        List<Long> skuIds = skus.stream().map(SkuInfoEntity::getSkuId).collect(Collectors.toList());
        Map<Long, Boolean> stockMap = null;
        try {
            R hasStock = wareFeignService.hasstock(skuIds);
            List<SkuHasStockVo> data = FeignUtil.formatListClass(hasStock, SkuHasStockVo.class);
            stockMap = data.stream()
                    .collect(Collectors.toMap(SkuHasStockVo::getSkuId, SkuHasStockVo::getHasStock));
        } catch (Exception e) {
            log.error(e.getMessage());
        }

        // 查询当前sku的所有可以被用来检索的规格属性
        List<ProductAttrValueEntity> entities = productAttrValueService.baseAttrListForSpu(spuId);
        List<Long> attrIds = entities.stream()
                .map(ProductAttrValueEntity::getAttrId).collect(Collectors.toList());
        List<Long> searchAttrIds = attrService.selectSearchAttrIds(attrIds);
        Set<Long> idSet = new HashSet<>(searchAttrIds);
        List<SkuEsModel.Attrs> attrsList = entities.stream()
                .filter(item -> idSet.contains(item.getAttrId()))
                .map(q -> BeanUtil.copyProperties(q, SkuEsModel.Attrs.class))
                .collect(Collectors.toList());

        // 组装需要的sku信息
        Map<Long, Boolean> finalStockMap = stockMap;
        List<SkuEsModel> collect = skus.stream().map(q -> {
            SkuEsModel esModel = BeanUtil.copyProperties(q, SkuEsModel.class);
            // 修改信息，拼接回显
            esModel.setSkuPrice(q.getPrice());
            esModel.setSkuImg(q.getSkuDefaultImg());

            // 品牌和分类的名称信息
            esModel.setBrandName(brand.getName());
            esModel.setBrandImg(brand.getLogo());
            esModel.setCatalogName(category.getName());

            // 设置库存信息
            esModel.setHasStock(finalStockMap.get(q.getSkuId()) == null ?
                    false : finalStockMap.get(q.getSkuId()));

            // 设置可被检索的属性
            esModel.setAttrs(attrsList);
            return esModel;
        }).collect(Collectors.toList());

        // 将数据发送给es进行保存
        R r = searchFeignService.productStatusUp(collect);
        if (r.success()) {
            SpuInfoEntity spuInfoEntity = new SpuInfoEntity();
            spuInfoEntity.setId(spuId);
            spuInfoEntity.setPublishStatus(ProductStatusEnum.UP.getCode());
            spuInfoEntity.setUpdateTime(new Date());
            baseMapper.updateById(spuInfoEntity);
        } else {
            // TODO: 2021/7/26 重复调用，接口幂等性，重试机制？
            // feign自己有重试机制
        }
    }

    /**
     * 根据skuId查询spu的信息
     * @param skuId
     * @return
     */
    @Override
    public SpuInfoEntity getSpuInfoBySkuId(Long skuId) {
        //先查询sku表里的数据
        SkuInfoEntity skuInfoEntity = skuInfoService.getById(skuId);
        //获得spuId
        Long spuId = skuInfoEntity.getSpuId();
        //再通过spuId查询spuInfo信息表里的数据
        SpuInfoEntity spuInfoEntity = this.baseMapper.selectById(spuId);
        //查询品牌表的数据获取品牌名
        BrandEntity brandEntity = brandService.getById(spuInfoEntity.getBrandId());
        spuInfoEntity.setBrandName(brandEntity.getName());
        return spuInfoEntity;
    }

}